package cn.nexd.app.presenter;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.text.format.Time;
import android.util.Log;

import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.nexd.app.NexdApplication;
import cn.nexd.app.activity.inter.IMainActivityView;
import cn.nexd.app.arsenal.StepDetector;
import cn.nexd.app.model.OperaRecord;
import cn.nexd.app.presenter.inter.ICollectionPresenter;
import cn.nexd.app.util.BasicPhoneInformation;
import cn.nexd.app.util.DateUtil;
import cn.nexd.app.util.FileUtil;
import cn.nexd.collector.NexdCollector;
import cn.nexd.collector.NexdCollectorAgent;
import cn.nexd.collector.NexdCollectorConfiguration;
import cn.nexd.collector.bean.BeaconScannerResult;
import cn.nexd.collector.bean.WifiCollectorResult;
import cn.nexd.collector.listener.BeaconCollectorListener;
import cn.nexd.collector.listener.WifiCollectorListener;
//import cn.nexd.location.NexdLocationAgent;
//import cn.nexd.location.NexdLocationConfig;
//import cn.nexd.location.collector.bean.BluetoothCollectorResult;
//import cn.nexd.location.collector.bean.WifiCollectorResult;

/**
 * 采集业务处理
 * <p/>
 * Created by wangxu on 16/3/16.
 */
public class ICollectionPresenterImpl implements ICollectionPresenter {


    private final String TAG = this.getClass().getSimpleName();
    private Context context;
    private NexdCollectorConfiguration.Buidler collectConfig = null;
    private NexdCollectorAgent locationAgent;

    //    private NexdLocationConfig.Buidler locationConfig = null;
    //    private NexdLocationAgent locationAgent;
    private IMainActivityView iMainActivityView;


    private SensorManager sensorManager;
    private float[] gyroMatrix;
    private float[] dataVector;
    private static final double NS2S = 1.0 / 1000000000.0;
    private final float[] deltaRotationVector = new float[4];

    private Sensor sensor_type_accelerometer;
    private Sensor sensor_type_linear_acceleration;
    private Sensor sensor_type_gyroscope;
    private Sensor sensor_type_gravity;
    private Sensor sensor_type_magnetic_field;
    private Sensor sensor_type_rotation_vector;
    private Sensor sensor_type_orientation;
    private Sensor sensor_type_pressure;
    private Sensor sensor_type_ambient_temperature;
    private Sensor sensor_type_light;
    private Sensor sensor_type_proximity;
    private Sensor sensor_type_relative_humidity;
    private Sensor sensor_type_game_rotation_vector;
    private Sensor sensor_type_geomagnetic_rotation_vector;
    private Sensor sensor_type_step_counter;
    private Sensor sensor_type_step_detector;
    private Sensor sensor_type_magnetic_field_uncalibrated;
    private Sensor sensor_type_gyroscope_uncalibrated;
    private DefaultSensorEventListenerForCollector defaultSensorEventListenerForCollector;
    private StepDetector stepDetector;
    private static StringBuilder wifiStringBuilder = new StringBuilder();
    private static StringBuilder sensorStringBuilder = new StringBuilder();
    private static StringBuilder bluetoothStringBuilder = new StringBuilder();
    private BasicPhoneInformation basicPhoneInformation;


    public ICollectionPresenterImpl(Context context, IMainActivityView iMainActivityView) {
        this.context = context;
        this.iMainActivityView = iMainActivityView;
        this.basicPhoneInformation = BasicPhoneInformation.getInstance(context);
    }

    private long counter = 0;
    private float lastStepCount = -1;
    private long timestamp = 0;
    private int counterCache = 0;


    @Override
    public void startCollect() {

        setCollectMode();
        counter = 0;
        counterCache = 0;
        stepDetector.clear();
        NexdApplication.baseFileName = NexdApplication.buildingName + "_" + NexdApplication.buildingId + "_" + NexdApplication.floorName + "_" + DateUtil.getCurrentByType(DateUtil.YYYYMMDDhhmmss) + "_" +
                NexdApplication.userEmial;
        NexdApplication.wifiDataFileName = NexdApplication.baseFileName + ".wifi";
        NexdApplication.bluetoothFileName = NexdApplication.baseFileName + ".bluetooth";
        NexdApplication.sensorFileName = NexdApplication.baseFileName + ".sensor";
        NexdApplication.zipFileName = NexdApplication.baseFileName;


        locationAgent.startCollector();
        registerListener();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void initSensors() {
        sensor_type_accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensor_type_linear_acceleration = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
        sensor_type_gyroscope = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
        sensor_type_gravity = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        sensor_type_magnetic_field = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        sensor_type_rotation_vector = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
        sensor_type_orientation = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        sensor_type_pressure = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
        sensor_type_ambient_temperature = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
        sensor_type_light = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        sensor_type_proximity = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sensor_type_relative_humidity = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
        sensor_type_game_rotation_vector = sensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR);
        sensor_type_geomagnetic_rotation_vector = sensorManager.getDefaultSensor(Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR);
        sensor_type_step_counter = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        sensor_type_step_detector = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        sensor_type_magnetic_field_uncalibrated = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED);
        sensor_type_gyroscope_uncalibrated = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE_UNCALIBRATED);
    }


    private void registerListener() {
        int sensorDelayNormal = 20000;
        //        int sensorDelayNormal = SensorManager.SENSOR_DELAY_NORMAL;
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_accelerometer, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_linear_acceleration, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_gyroscope, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_gravity, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_magnetic_field, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_rotation_vector, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_orientation, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_pressure, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_ambient_temperature, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_light, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_proximity, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_relative_humidity, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_game_rotation_vector, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_geomagnetic_rotation_vector, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_step_counter, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_step_detector, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_magnetic_field_uncalibrated, sensorDelayNormal);
        sensorManager.registerListener(defaultSensorEventListenerForCollector, sensor_type_gyroscope_uncalibrated, sensorDelayNormal);
        //        sensorManager.flush(defaultSensorEventListenerForCollector);
    }

    private void unRegisterListener() {
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_accelerometer);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_linear_acceleration);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_gyroscope);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_gravity);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_magnetic_field);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_rotation_vector);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_orientation);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_pressure);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_ambient_temperature);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_light);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_proximity);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_relative_humidity);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_game_rotation_vector);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_geomagnetic_rotation_vector);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_step_counter);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_step_detector);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_magnetic_field_uncalibrated);
        sensorManager.unregisterListener(defaultSensorEventListenerForCollector, sensor_type_gyroscope_uncalibrated);
    }


    @Override
    public void stopCollet() {
        locationAgent.stopCollector();
        unRegisterListener();
    }

    private void setCollectMode() {

        if (NexdApplication.mix) {
            collectConfig.setWifiCollectorEnable(true);
            collectConfig.setBluetoothCollectorEnable(true);
        } else {
            collectConfig.setWifiCollectorEnable(NexdApplication.wifi);
            collectConfig.setBluetoothCollectorEnable(NexdApplication.bluetooth);
        }
        collectConfig.setAppkey("");
        collectConfig.setBluetoothCollectorRate(1000);
        collectConfig.setBeaconCollectorDelay(1000);
        collectConfig.setWifiCollectorDelay(1000);
        collectConfig.setWifiCollectorRate(1000);
        locationAgent.setCollectorConfiguration(collectConfig.build());

        if (NexdApplication.mix || NexdApplication.wifi) {
            locationAgent.setWifiCollectorListener(new WifiCollectorListener() {
                @Override
                public void onCollectionStart() {
                    Log.d(TAG, "onCollectionStart: start Collect Wi-fi");
                }

                @Override
                public void onCollectionSuccess(List<WifiCollectorResult> collectorResults) {
                    Log.d(TAG, "onCollectionSuccess: Wi-fi collect success" + Arrays.toString(collectorResults.toArray()));
                    Log.d("collector_test_data", "####Wifi " + collectorResults.size());
                    iMainActivityView.resetEnvironmentWifi(String.valueOf(collectorResults.size()));
                    ICollectionPresenterImpl.this.wifiCollectorResults = collectorResults;
                }

                @Override
                public void onCollectorFailed(NexdCollector.CollectorState collectorState) {
                    Log.d(TAG, "Wifi_Failed " + collectorState);
                }

                @Override
                public void onCollectorInterrupt(NexdCollector.CollectorState collectorState) {
                    Log.d(TAG, "onCollectorInterrupt: Wi-fi Interrupt" + collectorState);
                }
            });
        } else {
            locationAgent.setWifiCollectorListener(null);
            if (wifiCollectorResults != null) {
                wifiCollectorResults.clear();
            }
        }
        if (NexdApplication.mix || NexdApplication.bluetooth) {
            locationAgent.setBeaconCollectorListener(new BeaconCollectorListener() {
                @Override
                public void onCollectionStart() {
                    Log.d(TAG, "onCollectionStart: Beacon collect start");
                }

                @Override
                public void onCollectionSuccess(List<BeaconScannerResult> collectorResults) {
                    Log.d(TAG, "onCollectionSuccess: beacon collect success" + Arrays.toString(collectorResults.toArray()));
                    iMainActivityView.resetEnvironmentBeacon(String.valueOf(collectorResults.size()));
                    ICollectionPresenterImpl.this.bluetoothCollectorResults = collectorResults;
                    Log.d("collector_test_data", "####Bluetooth " + collectorResults.size());

                }

                @Override
                public void onCollectorFailed(NexdCollector.CollectorState collectorState) {
                    Log.d(TAG, "onCollectorFailed: beacon collect failed" + collectorState);
                }

                @Override
                public void onCollectorInterrupt(NexdCollector.CollectorState collectorState) {
                    Log.d(TAG, "onCollectorInterrupt: beacon collect interrupt" + collectorState);
                }
            });
        } else {
            locationAgent.setBeaconCollectorListener(null);
            if (bluetoothCollectorResults != null) {
                bluetoothCollectorResults.clear();
            }
        }

        //        if ()
        //        if (NexdApplication.wifi) {
        //            locationConfig.setLocationMode(NexdLocationConfig.LocationMode.WIFI_ONLY);
        //        } else if (NexdApplication.bluetooth) {
        //            locationConfig.setLocationMode(NexdLocationConfig.LocationMode.BLUETOOTH_ONLY);
        //        } else if (NexdApplication.mix) {
        //            locationConfig.setLocationMode(NexdLocationConfig.LocationMode.MIX);
        //        }
        //        locationConfig.setLocationRate(500);
        //        NexdLocationConfig nexdLocationConfig = locationConfig.build();
        //        locationAgent.setLocationConfig(nexdLocationConfig);
    }


    @Override
    public void initCollector() {
        stepDetector = new StepDetector();
        locationAgent = NexdCollectorAgent.getCollectorAgent(context);
        collectConfig = new NexdCollectorConfiguration.Buidler();
        locationAgent.setCollectorConfiguration(collectConfig.build());
        //        locationAgent.setWifiCollectorListener(new WifiCollectorListener() {
        //            @Override
        //            public void onCollectionStart() {
        //                Log.d(TAG, "onCollectionStart: start Collect Wi-fi");
        //            }
        //
        //            @Override
        //            public void onCollectionSuccess(List<WifiCollectorResult> collectorResults) {
        //                Log.d(TAG, "onCollectionSuccess: Wi-fi collect success" + Arrays.toString(collectorResults.toArray()));
        //                Log.d("collector_test_data", "####Wifi " + collectorResults.size());
        //                iMainActivityView.resetEnvironmentWifi(String.valueOf(collectorResults.size()));
        //                ICollectionPresenterImpl.this.wifiCollectorResults = collectorResults;
        //            }
        //
        //            @Override
        //            public void onCollectorFailed(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "Wifi_Failed " + collectorState);
        //            }
        //
        //            @Override
        //            public void onCollectorInterrupt(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "onCollectorInterrupt: Wi-fi Interrupt" + collectorState);
        //            }
        //        });
        //
        //        locationAgent.setBeaconCollectorListener(new BeaconCollectorListener() {
        //            @Override
        //            public void onCollectionStart() {
        //                Log.d(TAG, "onCollectionStart: Beacon collect start");
        //            }
        //
        //            @Override
        //            public void onCollectionSuccess(List<BeaconScannerResult> collectorResults) {
        //                Log.d(TAG, "onCollectionSuccess: beacon collect success" + Arrays.toString(collectorResults.toArray()));
        //                iMainActivityView.resetEnvironmentBeacon(String.valueOf(collectorResults.size()));
        //                ICollectionPresenterImpl.this.bluetoothCollectorResults = collectorResults;
        //                Log.d("collector_test_data", "####Bluetooth " + collectorResults.size());
        //
        //            }
        //
        //            @Override
        //            public void onCollectorFailed(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "onCollectorFailed: beacon collect failed" + collectorState);
        //            }
        //
        //            @Override
        //            public void onCollectorInterrupt(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "onCollectorInterrupt: beacon collect interrupt" + collectorState);
        //            }
        //        });

        //        locationAgent.setMixCollectorListener(new MixCollectorListener() {
        //            @Override
        //            public void onCollectionStart() {
        //                Log.d(TAG, "onCollectionStart: ");
        //            }
        //
        //            @Override
        //            public void onCollectionSuccess(List<MixCollectorResult> collectorResults) {
        //                Log.d(TAG, "onCollectionSuccess: ");
        //            }
        //
        //            @Override
        //            public void onCollectorFailed(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "onCollectorFailed: ");
        //            }
        //
        //            @Override
        //            public void onCollectorInterrupt(NexdCollector.CollectorState collectorState) {
        //                Log.d(TAG, "onCollectorInterrupt: ");
        //            }
        //        });

        //        locationAgent = NexdLocationAgent.getLocationAgent();
        //        locationAgent.setContext(context);
        //        locationConfig = new NexdLocationConfig.Buidler();
        //        locationConfig.setAppkey("");
        //        locationAgent.setWifiCollectorListener(new cn.nexd.location.collector.core.Collector.WifiCollectorListener() {
        //            @Override
        //            public void onFailed(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskFailedType, String collectorResultTaskFailedMessage) {
        //                Log.d("collector_test_data", "####Wifi " + collectorResultTaskFailedMessage);
        //            }
        //
        //            @Override
        //            public void onSuccess(long collectorResultTaskId, long collectorResultTaskTime, List<WifiCollectorResult> wifiCollectorResults) {
        //                Log.d("collector_test_data", "####Wifi " + wifiCollectorResults.size());
        //                iMainActivityView.resetEnvironmentWifi(String.valueOf(wifiCollectorResults.size()));
        //                ICollectionPresenterImpl.this.wifiCollectorResults = wifiCollectorResults;
        //                //            MainActivity.this.wifiCollectorResults.clear();
        //                //            MainActivity.this.wifiCollectorResults.addAll(wifiCollectorResults);
        //
        //            }
        //
        //            @Override
        //            public void onStop(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskStopType, String collectorResultTaskStopMessage) {
        //                Log.d("collector_test_data", "####Wifi " + collectorResultTaskStopMessage);
        //            }
        //        });
        //        locationAgent.setBluetoothCollectorListener(new cn.nexd.location.collector.core.Collector.BluetoothCollectorListener() {
        //            @Override
        //            public void onFailed(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskFailedType, String collectorResultTaskFailedMessage) {
        //                Log.d("collector_test_data", "####Bluetooth " + collectorResultTaskFailedMessage);
        //            }
        //
        //            @Override
        //            public void onStop(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskStopType, String collectorResultTaskStopMessage) {
        //                Log.d("collector_test_data", "####Bluetooth " + collectorResultTaskStopMessage);
        //            }
        //
        //            @Override
        //            public void onSuccess(long collectorResultTaskId, long collectorResultTaskTime, List<BluetoothCollectorResult> bluetoothCollectorResults) {
        //                iMainActivityView.resetEnvironmentBeacon(String.valueOf(bluetoothCollectorResults.size()));
        //                ICollectionPresenterImpl.this.bluetoothCollectorResults = bluetoothCollectorResults;
        //                //            MainActivity.this.bluetoothCollectorResults.clear();
        //                //            MainActivity.this.bluetoothCollectorResults.addAll(bluetoothCollectorResults);
        //                Log.d("collector_test_data", "####Bluetooth " + bluetoothCollectorResults.size());
        //            }
        //        });
        //        locationAgent.setLocationListener(null);
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        defaultSensorEventListenerForCollector = new DefaultSensorEventListenerForCollector(context);
        initSensors();
        // 初始化存放数据的数组
        dataVector = new float[69];
        for (int i = 0, len = dataVector.length; i < len; i++) {
            dataVector[i] = -1;
        }
        gyroMatrix = new float[]{1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                0.0f, 1.0f};
    }

    @Override
    public void buildFile() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 保存
                if (sensorStringBuilder.length() > 0) {
                    new SaveDataTask(sensorStringBuilder.toString(), wifiStringBuilder.toString(), bluetoothStringBuilder.toString()).execute();
                    sensorStringBuilder.setLength(0);
                    wifiStringBuilder.setLength(0);
                    bluetoothStringBuilder.setLength(0);
                }
                // 打包文件

                final StringBuilder zipFilePathBuffer = new StringBuilder();
                zipFilePathBuffer
                        .append(NexdApplication.BASE_FILE_PATH)
                        .append(File.separator)
                        .append(NexdApplication.baseFilePath)
                        .append(File.separator)
                        .append(NexdApplication.baseFileName);

                final StringBuilder sourcePathBuffer = new StringBuilder();
                sourcePathBuffer
                        .append(NexdApplication.BASE_FILE_PATH)
                        .append(File.separator)
                        .append(NexdApplication.baseFilePath)
                        .append(File.separator)
                        .append(NexdApplication.buildingId)
                        .append(File.separator);

                try {
                    //  记录操作
                    NexdApplication.operaRecord.add(zipFilePathBuffer.toString());
                    FileUtil.compressFile(FileUtil.buildFile(sourcePathBuffer.toString()), zipFilePathBuffer.toString());
                    FileUtil.deleteFileOrDir(sourcePathBuffer.toString());
                } catch (Exception e) {
                    MobclickAgent.reportError(context, e);
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    MobclickAgent.reportError(context, e);
                    e.printStackTrace();
                }
                iMainActivityView.resetAllView();
            }
        }).start();
    }

    @Override
    public boolean checkEnvironmentState() {

        if (NexdApplication.mix) {
            WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            return wifimanager.isWifiEnabled() && mBluetoothAdapter.isEnabled();
        } else if (NexdApplication.wifi) {
            WifiManager wifimanager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            return wifimanager.isWifiEnabled();

        } else if (NexdApplication.bluetooth) {
            return BluetoothAdapter.getDefaultAdapter().isEnabled();
        }
        return false;
    }

    @Override
    public void saveOperaRecord() {

        if (NexdApplication.userEmial.contains("test")) {
            return;
        }
        NexdApplication.exitTime = DateUtil.getCurrentByType(DateUtil.YYYYMMDDhhmmss);
        // 将数据存储在数据表中
        OperaRecord operaRecord = new OperaRecord();
        operaRecord.setBuildingid(NexdApplication.buildingId);
        operaRecord.setCreateTime(DateUtil.getCurrentByType(DateUtil.YYYYMMDDhhmmss));
        operaRecord.setStartTime(NexdApplication.startTime);
        operaRecord.setEndTime(NexdApplication.exitTime);
        operaRecord.setMallName(NexdApplication.buildingName);
        operaRecord.setLat(NexdApplication.lat);
        operaRecord.setLng(NexdApplication.lng);
        operaRecord.setUserName(NexdApplication.userEmial);
        operaRecord.setMemo(NexdApplication.floorName);
        operaRecord.setOperaRecord(NexdApplication.baseFileName);

        Log.d("OperaRecord", operaRecord.toString());
        NexdApplication.liteOrm.save(operaRecord);
    }

    @Override
    public void getDeviceInfo() {
        iMainActivityView.initDeviceInfo("当前版本号:v1.0.0_" + basicPhoneInformation.getPhoneModel() + "_" + basicPhoneInformation.getAPILevel());
    }

    private List<WifiCollectorResult> wifiCollectorResults = new ArrayList<WifiCollectorResult>();
    //BeaconScannerResult
    //    private List<BluetoothCollectorResult> bluetoothCollectorResults = new ArrayList<BluetoothCollectorResult>();
    private List<BeaconScannerResult> bluetoothCollectorResults = new ArrayList<BeaconScannerResult>();

    //    public class DefaultBluetoothCollectorListenerForCollector implements cn.nexd.location.collector.core.Collector.BluetoothCollectorListener {
    //
    //        @Override
    //        public void onFailed(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskFailedType, String collectorResultTaskFailedMessage) {
    //            Log.d("collector_test_data", "####Bluetooth " + collectorResultTaskFailedMessage);
    //        }
    //
    //        @Override
    //        public void onStop(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskStopType, String collectorResultTaskStopMessage) {
    //            Log.d("collector_test_data", "####Bluetooth " + collectorResultTaskStopMessage);
    //        }
    //
    //        @Override
    //        public void onSuccess(long collectorResultTaskId, long collectorResultTaskTime, List<BluetoothCollectorResult> bluetoothCollectorResults) {
    //            iMainActivityView.resetEnvironmentBeacon(String.valueOf(bluetoothCollectorResults.size()));
    //            ICollectionPresenterImpl.this.bluetoothCollectorResults = bluetoothCollectorResults;
    //            //            MainActivity.this.bluetoothCollectorResults.clear();
    //            //            MainActivity.this.bluetoothCollectorResults.addAll(bluetoothCollectorResults);
    //            Log.d("collector_test_data", "####Bluetooth " + bluetoothCollectorResults.size());
    //        }
    //    }


    public class DefaultSensorEventListenerForCollector implements SensorEventListener {

        public DefaultSensorEventListenerForCollector(Context context) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            switch (event.sensor.getType()) {
                case Sensor.TYPE_ACCELEROMETER:
                    //数组 dataVector 的第 11 12 13 个元素
                    System.arraycopy(event.values, 0, dataVector, 10, 3);
                    ICollectionPresenterImpl.this.timestamp = event.timestamp;
                    Time t = new Time();
                    t.setToNow();
                    dataVector[43] = stepDetector.detect(event.values[2] / SensorManager.STANDARD_GRAVITY);
                    Log.d("stepTextView", " 步数 ===        " + dataVector[43]);
                    if (dataVector[43] == 1 || dataVector[56] != lastStepCount) {
                        lastStepCount = dataVector[56];
                        iMainActivityView.resetEnvironmentStep(String.valueOf(stepDetector.getStepCount()));
                    }

                    if (counterCache >= 20) {

                        // 拼接数据
                        wifiStringBuilder.append(appendWiFiString(wifiCollectorResults, counter));
                        bluetoothStringBuilder.append(appendBluetoothString(bluetoothCollectorResults, counter));
                        sensorStringBuilder.append(appendSensorString(dataVector, counter, timestamp));
                        counter = counter + 1;
                    }

                    // TODO 测试最大写入速度
                    if (sensorStringBuilder.length() >= 65535 * 4) {
                        // 写入
                        new SaveDataTask(sensorStringBuilder.toString(), wifiStringBuilder.toString(), bluetoothStringBuilder.toString()).execute();
                        wifiStringBuilder.setLength(0);
                        sensorStringBuilder.setLength(0);
                        bluetoothStringBuilder.setLength(0);
                    }
                    counterCache = counterCache + 1;
                    break;
                case Sensor.TYPE_LINEAR_ACCELERATION:
                    System.arraycopy(event.values, 0, dataVector, 13, 3);
                    break;
                case Sensor.TYPE_GYROSCOPE:
                    gyroHandler(event);
                    break;
                case Sensor.TYPE_GRAVITY:
                    System.arraycopy(event.values, 0, dataVector, 16, 3);
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD:
                    System.arraycopy(event.values, 0, dataVector, 25, 3);
                    break;
                case Sensor.TYPE_ROTATION_VECTOR:
                    System.arraycopy(event.values, 0, dataVector, 28, 3);
                    break;
                case Sensor.TYPE_ORIENTATION:
                    System.arraycopy(event.values, 0, dataVector, 31, 3);
                    break;
                case Sensor.TYPE_PRESSURE:
                    System.arraycopy(event.values, 0, dataVector, 35, 1);
                    break;
                case Sensor.TYPE_AMBIENT_TEMPERATURE:
                    System.arraycopy(event.values, 0, dataVector, 36, 1);
                    break;
                case Sensor.TYPE_LIGHT:
                    System.arraycopy(event.values, 0, dataVector, 37, 1);
                    break;
                case Sensor.TYPE_PROXIMITY:
                    System.arraycopy(event.values, 0, dataVector, 38, 1);
                    break;
                case Sensor.TYPE_RELATIVE_HUMIDITY:
                    System.arraycopy(event.values, 0, dataVector, 39, 1);
                    break;
                case Sensor.TYPE_GAME_ROTATION_VECTOR:
                    System.arraycopy(event.values, 0, dataVector, 50, 3);
                    break;
                case Sensor.TYPE_GEOMAGNETIC_ROTATION_VECTOR:
                    System.arraycopy(event.values, 0, dataVector, 53, 3);
                    break;
                case Sensor.TYPE_STEP_COUNTER:
                    System.arraycopy(event.values, 0, dataVector, 56, 1);
                    break;
                case Sensor.TYPE_STEP_DETECTOR:
                    break;
                case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
                    System.arraycopy(event.values, 0, dataVector, 57, 6);
                    break;
                case Sensor.TYPE_GYROSCOPE_UNCALIBRATED:
                    System.arraycopy(event.values, 0, dataVector, 63, 6);
                    break;
                case Sensor.TYPE_SIGNIFICANT_MOTION:
                    break;

            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

        protected void gyroHandler(SensorEvent event) {

            // This timestep's delta rotation to be multiplied by the current
            // rotation
            // after computing it from the gyro sample data.
            if (timestamp != 0) {
                final double dT = (double) (event.timestamp - timestamp) * NS2S;
                // Axis of the rotation sample, not normalized yet.
                float axisX = event.values[0];
                float axisY = event.values[1];
                float axisZ = event.values[2];

                System.arraycopy(event.values, 0, dataVector, 19, 3);
                for (int i = 0; i < 3; i++) {
                    dataVector[44 + i] += (double) event.values[i] * dT;
                }
                // Calculate the angular speed of the sample
                float omegaMagnitude = (float) Math.sqrt(axisX * axisX + axisY
                        * axisY + axisZ * axisZ);

                // Normalize the rotation vector if it's big enough to get the
                // axis
                // (that is, EPSILON should represent your maximum allowable
                // margin of error)
                if (omegaMagnitude > Float.MIN_NORMAL) {
                    axisX /= omegaMagnitude;
                    axisY /= omegaMagnitude;
                    axisZ /= omegaMagnitude;
                }

                // Integrate around this axis with the angular speed by the
                // timestep
                // in order to get a delta rotation from this sample over the
                // timestep
                // We will convert this axis-angle representation of the delta
                // rotation
                // into a quaternion before turning it into the rotation matrix.
                float thetaOverTwo = (float) (omegaMagnitude * dT / 2.0f);
                float sinThetaOverTwo = (float) Math.sin(thetaOverTwo);
                float cosThetaOverTwo = (float) Math.cos(thetaOverTwo);
                deltaRotationVector[0] = sinThetaOverTwo * axisX;
                deltaRotationVector[1] = sinThetaOverTwo * axisY;
                deltaRotationVector[2] = sinThetaOverTwo * axisZ;
                deltaRotationVector[3] = cosThetaOverTwo;
            }
            timestamp = event.timestamp;
            float[] deltaRotationMatrix = new float[9];
            float[] orientation = new float[3];
            SensorManager.getRotationMatrixFromVector(deltaRotationMatrix,
                    deltaRotationVector);
            gyroMatrix = matrixMultiplication(gyroMatrix, deltaRotationMatrix);
            //        System.arraycopy(gyroMatrix, 0, dataVector, 1, 9);
            // User code should concatenate the delta rotation we computed with
            // the current rotation
            // in order to get the updated rotation.
            // rotationCurrent = rotationCurrent * deltaRotationMatrix;
            SensorManager.getOrientation(gyroMatrix, orientation);
            System.arraycopy(orientation, 0, dataVector, 22, 3);
            // gyroYawTextView.setText(String.valueOf(orientation[0]));
            // gyroPitchTextView.setText(String.valueOf(orientation[1]));
            // gyroRollTextView.setText(String.valueOf(orientation[2]));
        }
    }

    private float[] matrixMultiplication(float[] A, float[] B) {
        float[] result = new float[9];

        result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
        result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
        result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];

        result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
        result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
        result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];

        result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
        result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
        result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];

        return result;
    }

    private String appendSensorString(float[] dataVector, long counter, long time) {
        Log.d("counter_test", "appendSensorString " + counter);
        StringBuilder stringBuffer_sensor = new StringBuilder();
        stringBuffer_sensor.append(counter).append(" ");
        for (int i = 1; i < 44; i++) {
            stringBuffer_sensor.append(dataVector[i]).append(' ');
        }
        stringBuffer_sensor.append(time).append(' ');
        for (int i = 44; i < 69; i++) {
            stringBuffer_sensor.append(dataVector[i]).append(' ');
        }
        stringBuffer_sensor.append("\n");
        return stringBuffer_sensor.toString();
    }

    //    private String appendWiFiString(List<WifiCollectorResult> wifiCollectorResults, long counter) {
    //        Log.d("counter_test", "appendWiFiString " + counter);
    //        StringBuilder stringBuffer_wifi = new StringBuilder();
    //        stringBuffer_wifi.append(counter).append(" ");
    //        for (int i = 0, len = wifiCollectorResults.size(); i < len; i++) {
    //            stringBuffer_wifi.append(wifiCollectorResults.get(i).getBSSID()).append(" ").append(wifiCollectorResults.get(i).getLevel()).append(" ");
    //        }
    //        stringBuffer_wifi.append("\n");
    //        return stringBuffer_wifi.toString();
    //    }

    //    private String appendBluetoothString(List<BluetoothCollectorResult> bluetoothCollectorResults, long counter) {
    //        Log.d("counter_test", "appendBluetoothString " + counter);
    //        StringBuilder stringBuffer_bt = new StringBuilder();
    //        stringBuffer_bt.append(counter).append(" ");
    //        for (int i = 0, len = bluetoothCollectorResults.size(); i < len; i++) {
    //            stringBuffer_bt.append(bluetoothCollectorResults.get(i).getAddress()).append(" ").append(bluetoothCollectorResults.get(i).getRssi()).append(" ");
    //        }
    //
    //        stringBuffer_bt.append("\n");
    //        return stringBuffer_bt.toString();
    //    }
    private String appendWiFiString(List<WifiCollectorResult> wifiCollectorResults, long counter) {
        Log.d("counter_test", "appendWiFiString " + counter);
        StringBuilder stringBuffer_wifi = new StringBuilder();
        stringBuffer_wifi.append(counter).append(" ");
        for (int i = 0, len = wifiCollectorResults.size(); i < len; i++) {
            stringBuffer_wifi.append(wifiCollectorResults.get(i).getWifiAddress()).append(" ").append(wifiCollectorResults.get(i).getRssi()).append(" ");
        }
        stringBuffer_wifi.append("\n");
        return stringBuffer_wifi.toString();
    }

    private String appendBluetoothString(List<BeaconScannerResult> bluetoothCollectorResults, long counter) {
        Log.d("counter_test", "appendBluetoothString " + counter);
        StringBuilder stringBuffer_bt = new StringBuilder();
        stringBuffer_bt.append(counter).append(" ");
        for (int i = 0, len = bluetoothCollectorResults.size(); i < len; i++) {
            stringBuffer_bt.append(bluetoothCollectorResults.get(i).getBeaconAddress()).append(" ").append(bluetoothCollectorResults.get(i).getRssi()).append(" ");
        }

        stringBuffer_bt.append("\n");
        return stringBuffer_bt.toString();
    }

    private class SaveDataTask extends AsyncTask {

        private String sensor;
        private String wifi;
        private String bt;

        public SaveDataTask(String sensor, String wifi, String bt) {
            this.sensor = sensor;
            this.wifi = wifi;
            this.bt = bt;
        }

        @Override
        protected Object doInBackground(Object[] params) {
            try {

                long firstTime = System.currentTimeMillis();
                final StringBuilder filePath = new StringBuilder();
                filePath.append(NexdApplication.BASE_FILE_PATH)
                        .append(File.separator)
                        .append(NexdApplication.baseFilePath)
                        .append(File.separator)
                        .append(NexdApplication.buildingId)
                        .append(File.separator);

                final String wifiPath = filePath.toString() + NexdApplication.wifiDataFileName;
                FileUtil.writeFile(wifiPath, wifi);

                final String sensorPath = filePath.toString() + NexdApplication.sensorFileName;
                FileUtil.writeFile(sensorPath, sensor);

                final String bluetoothPath = filePath.toString() + NexdApplication.bluetoothFileName;
                FileUtil.writeFile(bluetoothPath, bt);

                long endTime = System.currentTimeMillis();

                Log.i("write file time = ", String.valueOf(endTime - firstTime));
            } catch (IOException e) {
                MobclickAgent.reportError(context, e);
            }
            return null;
        }
    }

    //    public class DefaultWifiCollectorListenerForCollector implements cn.nexd.location.collector.core.Collector.WifiCollectorListener {
    //
    //        @Override
    //        public void onFailed(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskFailedType, String collectorResultTaskFailedMessage) {
    //            Log.d("collector_test_data", "####Wifi " + collectorResultTaskFailedMessage);
    //        }
    //
    //        @Override
    //        public void onSuccess(long collectorResultTaskId, long collectorResultTaskTime, List<WifiCollectorResult> wifiCollectorResults) {
    //            Log.d("collector_test_data", "####Wifi " + wifiCollectorResults.size());
    //            iMainActivityView.resetEnvironmentWifi(String.valueOf(wifiCollectorResults.size()));
    //            ICollectionPresenterImpl.this.wifiCollectorResults = wifiCollectorResults;
    //            //            MainActivity.this.wifiCollectorResults.clear();
    //            //            MainActivity.this.wifiCollectorResults.addAll(wifiCollectorResults);
    //
    //        }
    //
    //        @Override
    //        public void onStop(long collectorResultTaskId, long collectorResultTaskTime, int collectorResultTaskStopType, String collectorResultTaskStopMessage) {
    //            Log.d("collector_test_data", "####Wifi " + collectorResultTaskStopMessage);
    //        }
    //    }
}
